package com.itsu.spbspider.util;

import com.alibaba.fastjson.JSON;
import com.itsu.spbspider.entity.News;
import com.itsu.spbspider.mapper.NewsMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    }

    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(false);
    }

    public static <T> T getMapper(Class<T> mapperClass) {
        return sqlSessionFactory.openSession().getMapper(mapperClass);
    }

    public static void main(String[] args) {
        NewsMapper mapper = getMapper(NewsMapper.class);
        News news = mapper.getOne(37);
        System.out.println(JSON.toJSONString(news));
    }
}
